package org.ithang.lock;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;

public class MySQLLock implements Lock {

	private QueryRunner qr=null;
	private Random r=new Random(System.currentTimeMillis());
	
	public MySQLLock(DataSource ds){
		qr=new QueryRunner(ds);
	}
	
	@Override
	public void lock() {
		boolean locked=tryLock();
		if(!locked){
			try{
				Thread.sleep(r.nextInt(100));
			}catch(Exception e){
				//e.printStackTrace();
			}
			lock();
		}
	}

	@Override
	public void lockInterruptibly() throws InterruptedException {
		
	}

	@Override
	public boolean tryLock() {
		try{
			qr.update("insert into `lock`(`id`)values(?) ","locked");
		}catch(Exception e){
			//e.printStackTrace();
			return false;	
		}
		return true;
	}

	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		try{
			qr.update("insert into `lock`(`id`)values(?) ","locked");
		}catch(Exception e){
			return false;	
		}
		return true;
	}

	@Override
	public void unlock() {
		try{
			qr.update("delete from `lock` where id=?","locked");
		}catch(Exception e){
				
		}
	}

	@Override
	public Condition newCondition() {
		return null;
	}

}
